package com.dashang.feecenter.util;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;

/**
 * com.dashang.feecenter.util dashang-center
 *
 * @author duanxd
 * @version 1.0
 * @since 2021/11/17 09:19
 */
public class CommonUtils {
    /**
     * 反射获操做对象中某属性的值
     * @param obj
     * @param fieldName
     * @return
     */
    public static  Object optFieldValue(Object obj,String fieldName,String methodPrefix,Object... args){
        Class aClass = obj.getClass();
        String methodName = methodPrefix + fieldName.substring(0,1).toUpperCase()+fieldName.substring(1,fieldName.length());
        try {

            if ("get".equals(methodPrefix)){
                Method method = aClass.getMethod(methodName);
                Object invoke = method.invoke(obj);
                return invoke;
            }else if ("set".equals(methodPrefix)){
                List<Class> classList = new ArrayList<>();
                for (Object arg : args) {
                    classList.add(arg.getClass());
                }
                Method method = aClass.getMethod(methodName,classList.toArray(new Class[]{}));
                method.invoke(obj,args);
            }

        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 获取 某字节码对象中，拥有某注解的属性集合
     * @param aClass class对象
     * @param annotationClass 注解class对象
     * @return map key:属性对象  value：注解对象
     */
    public static <T extends Annotation>  Map<Field,T> getFieldsAnnotation(Class aClass, Class<T> annotationClass ){
        Field[] declaredFields = aClass.getDeclaredFields();
        Map<Field, T> fieldMap = new HashMap<>();
        for (Field declaredField : declaredFields) {
            T annotation = declaredField.getAnnotation(annotationClass);
            if (annotation != null){
                fieldMap.put(declaredField,annotation);
            }
        }
        return fieldMap;
    }

    /**
     * 把list中的值根据分隔符进行拼接
     * @param strings
     * @param separator
     * @return
     */
    public static String concatBySeparator(List<String> strings,String separator){
        StringBuffer buffer = new StringBuffer();
        for (String string : strings) {
            buffer.append(string).append(separator);
        }
        String substring = buffer.substring(0, buffer.length() - 1);

        return substring;
    }

    /**
     * 把 字符串根据 分隔符 分割，返回list集合
     * @param content
     * @param separator 分隔符
     * @return
     */
    public static List<String> splitBySeparator(String content,String separator){
        String[] split = content.split(separator);
        return Arrays.asList(split);
    }
}
